package com.visikard.application;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.visikard.item.VKregisterSession;
import com.visikard.system.VKregisterApiUrls;
import com.visikard.system.VKsessionStore;
import com.visikard.utility.Utils;

public class MyApplication extends Application {
	private static final String TAG = MyApplication.class.getSimpleName();

	public static MyApplication instance;

	/** application context */
	private Context mContext = null;
	public void setContext(Context C) {
		this.mContext = C;
	}

	public Context getContext() {
		return this.mContext;
	}

	/** visikard application session */
	private VKregisterSession mSession = null;
	public void saveSession(VKregisterSession session) {
		mSession = session;
		VKsessionStore.save(mSession, mContext);
	}
	public VKregisterSession restoreSession() {
		return VKsessionStore.restore(mContext);
	}
	public void removeSession() {
		VKsessionStore.clear(mContext);
	}
	
	public void saveSessionAddress(String address) {
		VKsessionStore.saveAddress(address, mContext);
	}
	
	public String restoreSessionAddress() {
		String location = VKsessionStore.restoreAdress(mContext);
		Log.d("NghiDo", "get address?: " + location);
		if(location == null)
			return "";
		else
			return location;
	}

	@Override
	public void onCreate() {
		Log.d(TAG, "onCreate()");
		super.onCreate();

		// create visikard application instance
		instance = this;

		// create visikard application context for context
		mContext = getApplicationContext();
		
//		mConfig = new VisikardConfig(mContext);

		// set default handler exception to catch
//		Thread.setDefaultUncaughtExceptionHandler(unCaughtExceptionHandler);

		// init application objects
		initObjects();
	}

	@Override
	public void onTerminate() {
		Log.d(TAG, "onTerminate()");
		super.onTerminate();

		// cancel all notification
		// TODO

		// stop all service
		// TODO

		// remove all broadcast
		// TODO
		
		// close db connection
		// TODO
	}

	/**
	 * init application objects
	 * load instances, connect db, session,...
	 */
	private void initObjects() {
		// create async task
		initUILImageLoader(this);
		// session
		//TODO
	}

	/**
	 * root handling of exception
	 */
	private Thread.UncaughtExceptionHandler unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
		@Override
		public void uncaughtException(Thread thread, Throwable ex) {
			Log.e(Constant.TAG, "Application crashed");
//			exitApp();
	        new Thread() {
	            @Override
	            public void run() {
	                Looper.prepare();
	                Toast.makeText(mContext, "Application crashed", Toast.LENGTH_LONG).show();	//getApplicationContext()
	                exitApp();
	                Looper.loop();
	            }
	        }.start();

	        try {
	            Thread.sleep(4000); // Let the Toast display before app will get shutdown
	        } catch (InterruptedException e) {
	            // Ignored.
	        }
		}
	};

	public void exitApp() {
		try {
			String httpurl = VKregisterApiUrls.buildHttps(
					VKregisterApiUrls.ACCOUNT_DELETE_SESSION,
					new String[] {
							String.valueOf(Constant.uid),
							Constant.loginSession});
			Utils.getConnectValueFromURL(httpurl);

			Constant.loginSession = null;
			Constant.username = null;
			Constant.password = null;
			Constant.idKard = -1;
			Constant.loginSession = null;
			Constant.uid = -1;

			// remove visikard session
			removeSession();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(10);
	}
	
	// TODO: move to application level
//	@SuppressWarnings({ "static-access", "deprecation" })
	public void logout() {
		Constant.loginSession = null;
		Constant.username = null;
		Constant.password = null;
		Constant.idKard = -1;
		Constant.loginSession = null;
		Constant.uid = -1;
		Constant.merchantLogo = "";
		Constant.merchantName = "";
		Constant.defaultProfile = null;

		// remove visikard session store
		removeSession();
	}
	
	public void initUILImageLoader(Context context) {
		com.nostra13.universalimageloader.core.ImageLoaderConfiguration config = new com.nostra13.universalimageloader.core.ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
				.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO).writeDebugLogs() // Remove for release app
				.memoryCacheSizePercentage(10).diskCacheSize(300 * 1024 * 1024)

				.build();
		// Initialize ImageLoader with configuration.
		com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
	}
}
